/*
 * CongressClientView.java
 */

package congressclient;

import com.surelution.congress.connector.CheckInInfo;
import com.surelution.congress.connector.Connector;
import com.surelution.congress.connector.MemberInfo;
import com.surelution.congress.connector.TimerInfo;
import com.surelution.core.drivers.tc400.ClockingRecord;
import com.surelution.core.drivers.tc400.PersonInfo;
import com.surelution.project.sms.ShortMessage;
import com.surelution.project.sms.SmsSender;
import com.surelution.project.sms.SmsSenderFactory;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.xml.sax.SAXException;

/**
 * The application's main frame.
 */
public class CongressClientView extends FrameView {

    public CongressClientView(SingleFrameApplication app) {
        super(app);

        initComponents();
        try {
            timers = Connector.getAllTimers();
            
            people = Connector.getAllMembers();
//            if(p != null) {
//                for(MemberInfo info:p) {
//                    PersonInfo pi = new PersonInfo();
//                    pi.setCardNo(info.getPassportId());
//                    pi.setName(info.getName());
//                    people.add(pi);
//                }
//            }
                  
            int i = 0;
            for(TimerInfo timer:timers) {
                JCheckBox cb = new JCheckBox();
                cb.setSize(200, 20);
                cb.setLocation(50, 50 * i++);
                cb.setText(timer.getIp());
                cb.setEnabled(false);
                cb.setSelected(true);
                timersListPane.add(cb);
            }
        } catch (ClientProtocolException ex) {
            Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
        }

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = CongressClientApp.getApplication().getMainFrame();
            aboutBox = new CongressClientAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        CongressClientApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        tabbedPane1 = new javax.swing.JTabbedPane();
        checkInDownloaderPane = new javax.swing.JPanel();
        timersListPane = new javax.swing.JPanel();
        btnDownloadCheckin = new javax.swing.JButton();
        smsSenderPane = new javax.swing.JPanel();
        rbStanding = new javax.swing.JRadioButton();
        rbAll = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtMsgContent = new javax.swing.JTextArea();
        btnSendMsg = new javax.swing.JButton();
        timerFormatterPane = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        lblConfirm = new javax.swing.JLabel();
        txtConfirm = new javax.swing.JTextField();
        pbFormat = new javax.swing.JProgressBar();
        jScrollPane2 = new javax.swing.JScrollPane();
        tpProcessMessage = new javax.swing.JTextPane();
        jLabel2 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        buttonGroup1 = new javax.swing.ButtonGroup();

        mainPanel.setName("mainPanel"); // NOI18N

        tabbedPane1.setName("tabbedPane1"); // NOI18N

        checkInDownloaderPane.setName("checkInDownloaderPane"); // NOI18N

        timersListPane.setName("timersListPane"); // NOI18N

        org.jdesktop.layout.GroupLayout timersListPaneLayout = new org.jdesktop.layout.GroupLayout(timersListPane);
        timersListPane.setLayout(timersListPaneLayout);
        timersListPaneLayout.setHorizontalGroup(
            timersListPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 582, Short.MAX_VALUE)
        );
        timersListPaneLayout.setVerticalGroup(
            timersListPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 181, Short.MAX_VALUE)
        );

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(congressclient.CongressClientApp.class).getContext().getResourceMap(CongressClientView.class);
        btnDownloadCheckin.setText(resourceMap.getString("btnDownloadCheckin.text")); // NOI18N
        btnDownloadCheckin.setName("btnDownloadCheckin"); // NOI18N
        btnDownloadCheckin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownloadCheckinActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout checkInDownloaderPaneLayout = new org.jdesktop.layout.GroupLayout(checkInDownloaderPane);
        checkInDownloaderPane.setLayout(checkInDownloaderPaneLayout);
        checkInDownloaderPaneLayout.setHorizontalGroup(
            checkInDownloaderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(checkInDownloaderPaneLayout.createSequentialGroup()
                .addContainerGap()
                .add(checkInDownloaderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(checkInDownloaderPaneLayout.createSequentialGroup()
                        .add(timersListPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, checkInDownloaderPaneLayout.createSequentialGroup()
                        .add(btnDownloadCheckin)
                        .add(32, 32, 32))))
        );
        checkInDownloaderPaneLayout.setVerticalGroup(
            checkInDownloaderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(checkInDownloaderPaneLayout.createSequentialGroup()
                .addContainerGap()
                .add(timersListPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(btnDownloadCheckin)
                .addContainerGap(112, Short.MAX_VALUE))
        );

        tabbedPane1.addTab(resourceMap.getString("checkInDownloaderPane.TabConstraints.tabTitle"), checkInDownloaderPane); // NOI18N

        smsSenderPane.setName("smsSenderPane"); // NOI18N

        buttonGroup1.add(rbStanding);
        rbStanding.setText(resourceMap.getString("rbStanding.text")); // NOI18N
        rbStanding.setName("rbStanding"); // NOI18N

        buttonGroup1.add(rbAll);
        rbAll.setSelected(true);
        rbAll.setText(resourceMap.getString("rbAll.text")); // NOI18N
        rbAll.setName("rbAll"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        txtMsgContent.setColumns(20);
        txtMsgContent.setRows(5);
        txtMsgContent.setName("txtMsgContent"); // NOI18N
        jScrollPane3.setViewportView(txtMsgContent);

        btnSendMsg.setText(resourceMap.getString("btnSendMsg.text")); // NOI18N
        btnSendMsg.setName("btnSendMsg"); // NOI18N
        btnSendMsg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendMsgActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout smsSenderPaneLayout = new org.jdesktop.layout.GroupLayout(smsSenderPane);
        smsSenderPane.setLayout(smsSenderPaneLayout);
        smsSenderPaneLayout.setHorizontalGroup(
            smsSenderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(smsSenderPaneLayout.createSequentialGroup()
                .add(smsSenderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(smsSenderPaneLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(smsSenderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(smsSenderPaneLayout.createSequentialGroup()
                                .add(jLabel3)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(rbAll)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(rbStanding))
                            .add(smsSenderPaneLayout.createSequentialGroup()
                                .add(jLabel4)
                                .add(18, 18, 18)
                                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 320, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(smsSenderPaneLayout.createSequentialGroup()
                        .add(140, 140, 140)
                        .add(btnSendMsg)))
                .addContainerGap(199, Short.MAX_VALUE))
        );
        smsSenderPaneLayout.setVerticalGroup(
            smsSenderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(smsSenderPaneLayout.createSequentialGroup()
                .addContainerGap()
                .add(smsSenderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(rbAll)
                    .add(rbStanding))
                .add(28, 28, 28)
                .add(smsSenderPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel4)
                    .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 124, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(41, 41, 41)
                .add(btnSendMsg)
                .addContainerGap(99, Short.MAX_VALUE))
        );

        tabbedPane1.addTab(resourceMap.getString("smsSenderPane.TabConstraints.tabTitle"), smsSenderPane); // NOI18N

        timerFormatterPane.setName("timerFormatterPane"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextPane1.setBackground(resourceMap.getColor("jTextPane1.background")); // NOI18N
        jTextPane1.setText(resourceMap.getString("jTextPane1.text")); // NOI18N
        jTextPane1.setName("jTextPane1"); // NOI18N
        jScrollPane1.setViewportView(jTextPane1);

        lblConfirm.setForeground(resourceMap.getColor("lblConfirm.foreground")); // NOI18N
        lblConfirm.setText(resourceMap.getString("lblConfirm.text")); // NOI18N
        lblConfirm.setName("lblConfirm"); // NOI18N

        txtConfirm.setText(resourceMap.getString("txtConfirm.text")); // NOI18N
        txtConfirm.setName("txtConfirm"); // NOI18N

        pbFormat.setName("pbFormat"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        tpProcessMessage.setName("tpProcessMessage"); // NOI18N
        jScrollPane2.setViewportView(tpProcessMessage);

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        org.jdesktop.layout.GroupLayout timerFormatterPaneLayout = new org.jdesktop.layout.GroupLayout(timerFormatterPane);
        timerFormatterPane.setLayout(timerFormatterPaneLayout);
        timerFormatterPaneLayout.setHorizontalGroup(
            timerFormatterPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(timerFormatterPaneLayout.createSequentialGroup()
                .add(timerFormatterPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(timerFormatterPaneLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel1))
                    .add(timerFormatterPaneLayout.createSequentialGroup()
                        .add(29, 29, 29)
                        .add(timerFormatterPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(timerFormatterPaneLayout.createSequentialGroup()
                                .add(lblConfirm, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 134, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(43, 43, 43)
                                .add(txtConfirm, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 225, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 573, Short.MAX_VALUE)))
                    .add(timerFormatterPaneLayout.createSequentialGroup()
                        .add(237, 237, 237)
                        .add(jButton2))
                    .add(timerFormatterPaneLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(pbFormat, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE))
                    .add(timerFormatterPaneLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel2))
                    .add(timerFormatterPaneLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 468, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        timerFormatterPaneLayout.setVerticalGroup(
            timerFormatterPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(timerFormatterPaneLayout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 96, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(timerFormatterPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblConfirm)
                    .add(txtConfirm, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButton2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(pbFormat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(31, 31, 31)
                .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 18, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        tabbedPane1.addTab(resourceMap.getString("timerFormatterPane.TabConstraints.tabTitle"), timerFormatterPane); // NOI18N

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(tabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 643, Short.MAX_VALUE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(tabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(congressclient.CongressClientApp.class).getContext().getActionMap(CongressClientView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 473, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(16, 16, 16))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void btnDownloadCheckinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadCheckinActionPerformed
        if(timers != null) {
            String insertSql = "insert into check_in_info(id, timer_id, timer_ip, person_id, check_in_time) values(?,?,?,?,?)";
            try {
                Connection conn = prepareConnection();
                PreparedStatement ps = conn.prepareStatement(insertSql);
                
                for(TimerInfo timer:timers) {
                    String ip = timer.getIp();
                    System.out.println("start download:" + ip);
                    String timerId = timer.getId();
                    com.surelution.core.drivers.tc400.Timer t = null;
                    List<ClockingRecord> record = null;
                    try{
                        t = com.surelution.core.drivers.tc400.Timer.openNet(ip);
                        record = t.getUnreadRecord();
                    } catch(Throwable e) {
                        System.err.println("can't open timer with ip:" + ip);
                    }
                    System.out.println("download from timer completed");
                    if(record != null) {
                        for(ClockingRecord cr : record) {
                            String id = UUID.randomUUID().toString();
                            ps.setString(1, id);
                            ps.setString(2, timerId);
                            ps.setString(3, ip);
                            ps.setString(4, cr.getPersonID() + "");
                            ps.setDate(5, new java.sql.Date(cr.getDate().getTime()));
//                            ps.addBatch();
                            ps.execute();
                        }
                    }
                    System.out.println("save to local db completed");
                }
//                ps.executeBatch();
                ps.close();
                conn.close();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        uploadCheckIn();
    }//GEN-LAST:event_btnDownloadCheckinActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if(lblConfirm.getText().equals(txtConfirm.getText())) {
            int option = JOptionPane.showConfirmDialog(this.getFrame(), "您确定要格式化签到机吗？","请确认", JOptionPane.YES_NO_OPTION);
            if(option == JOptionPane.YES_OPTION) {
                if(timers != null) {
                    int count = timers.size() * 3;
                    int completed = 0;
                    for(TimerInfo info : timers) {
                        com.surelution.core.drivers.tc400.Timer timer = null;
                        try{
                            timer = com.surelution.core.drivers.tc400.Timer.openNet(info.getIp());
                        }catch(Throwable e) {
                            
                        }
                        if(timer == null) {
                            makeProgress(3);
                        } else {
                            clearRecord(timer);
                            makeProgress(1);
                            clearPeople(timer);
                            makeProgress(1);
                            
                            
                            List<PersonInfo> pis = new ArrayList<PersonInfo>();
                            for(MemberInfo mi:people) {
                                PersonInfo pi = new PersonInfo();
                                pi.setCardNo(mi.getPassportId());
                                pi.setName(mi.getName());
                                pis.add(pi);
                            }
                            
                            pushPeople(timer, pis);
                            makeProgress(1);
                        }
                        
                    }
                }
            }
        } else {
            int option = JOptionPane.showConfirmDialog(this.getFrame(), "您输入的确认信息不对，请再三考虑！","请确认", JOptionPane.PLAIN_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnSendMsgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendMsgActionPerformed
        SmsSender sender = SmsSenderFactory.buildSender();
        String content = txtMsgContent.getText();
        List<ShortMessage> messages = new ArrayList<ShortMessage>();
        for(MemberInfo pi : people) {
            //it's much easier to understand
            //if(!(!pi.isStanding() && rbStanding.isSelected()))
            if(pi.isStanding() || rbAll.isSelected()) {
                ShortMessage message = new ShortMessage();
                message.setBody(content);
                message.setReceiver(pi.getMobileNumber());
                messages.add(message);
            }
        }
        sender.batchSend(messages);
    }//GEN-LAST:event_btnSendMsgActionPerformed
    
    private int totalTask = 0;
    private int complete = 0;
    private void makeProgress(int progress) {
        pbFormat.setValue((complete + progress) * 100/totalTask);
    }

    private void clearRecord(com.surelution.core.drivers.tc400.Timer timer) {
        timer.clearRecord();
    }
    
    private void clearPeople(com.surelution.core.drivers.tc400.Timer timer) {
        List<PersonInfo> people = timer.getAllPeople();
        if(people != null) {
            for(PersonInfo person : people) {
                timer.deletePerson(person.getId());
            }
        }
    }
    
    private void pushPeople(com.surelution.core.drivers.tc400.Timer timer, List<PersonInfo> people) {
        if(people != null) {
            for(PersonInfo person : people) {
                timer.addPerson(person);
            }
        }
    }
    
    private Connection prepareConnection() throws ClassNotFoundException, SQLException {
        Class.forName("org.hsqldb.jdbcDriver");
        java.sql.Connection conn = DriverManager.getConnection("jdbc:hsqldb:file:database/db","sa","");
        return conn;
    }
    
    private void uploadCheckIn() {
        System.out.println("start to upload record to server");
//        Connector.saveCheckInInfo(null);
        List<CheckInInfo> checks = new ArrayList<CheckInInfo>();
//        SimpleDateFormat sdf = new SimpleDateFormat("");
        try {
            Connection conn = prepareConnection();
            PreparedStatement ps = conn.prepareStatement("select id, timer_id, timer_ip, person_id, check_in_time from check_in_info where uploaded<>1 or uploaded is null");
            ResultSet rs = ps.executeQuery();
            if(rs != null) {
//                StringBuilder sb = new StringBuilder();
                while(rs.next()) {
                    String id = rs.getString("id");
                    String timerId = rs.getString("timer_id");
                    String timerIp = rs.getString("timer_ip");
                    String personId = rs.getString("person_id");
                    Timestamp checkInTime = rs.getTimestamp("check_in_time");
//                    sb.append(id);
//                    sb.append(",");
//                    sb.append(timerIp);
//                    sb.append(",");
//                    sb.append(personId);
//                    sb.append(",");
//                    String time = sdf.format(checkInTime);
//                    sb.append(time);
//                    sb.append("\n");
                    
                    
                    CheckInInfo info = new CheckInInfo();
                    info.setCheckTime(new Date(checkInTime.getTime()));
                    info.setPersonId(personId);
                    info.setTimerIp(timerIp);
                    info.setClientId(id);
                    checks.add(info);
                }
                rs.close();
            }
            
            ps.close();
            try {
                Connector.saveCheckInInfo(checks);
                //if no exception throw out, update local db to uploaded = 1
                ps = conn.prepareStatement("update check_in_info set uploaded=1");
                ps.execute();
                ps.close();
            } catch (ClientProtocolException ex) {
                Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
            }
            conn.close();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(CongressClientView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDownloadCheckin;
    private javax.swing.JButton btnSendMsg;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JPanel checkInDownloaderPane;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JLabel lblConfirm;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar pbFormat;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JRadioButton rbAll;
    private javax.swing.JRadioButton rbStanding;
    private javax.swing.JPanel smsSenderPane;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTabbedPane tabbedPane1;
    private javax.swing.JPanel timerFormatterPane;
    private javax.swing.JPanel timersListPane;
    private javax.swing.JTextPane tpProcessMessage;
    private javax.swing.JTextField txtConfirm;
    private javax.swing.JTextArea txtMsgContent;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    
    private List<TimerInfo> timers;
    
    private List<MemberInfo> people = new ArrayList<MemberInfo>();
}
